package authorized
import (
	"github.com/xinliangnote/go-gin-api/internal/repository/mysql/customer_auth"
	"github.com/xinliangnote/go-gin-api/internal/repository/mysql"
	"github.com/xinliangnote/go-gin-api/pkg/jwt"
	"github.com/xinliangnote/go-gin-api/pkg/errors"
	"github.com/xinliangnote/go-gin-api/configs"
	"time"
	"context"
)

func (s *serviceSt) LoginByVerifyCode(ctx context.Context, phone_number string, verify_code string)(string, error){
	cfg_sms := configs.Get().Sms
	cfg_jwt := configs.Get().Jwt
	// 1. 校验验证码 
	redis_key := cfg_sms.LoginKeyPrefix + phone_number
	if ret := s.cache.Exists(redis_key); !ret {
		return "", errors.New("验证码过期")
	}
	if value, err := s.cache.Get(redis_key); err != nil {
		return "", err
	} else if value != verify_code {
		return "", errors.New("验证码错误")
	}
	// 2. 校验成功，检测是否首次登陆
	qb  := customer_auth.NewQueryBuilder()
	qb.WherePhoneNumber(mysql.EqualPredicate, phone_number)
	if info, err := qb.QueryOne(s.db.GetDbR().WithContext(ctx)); err != nil{
		return "", err
	}else if info == nil{
		//  3.如果首次登陆向系统注册手机号
		user_info := customer_auth.NewModel()
		user_info.PhoneNumber = phone_number
		user_info.Status = 1
		user_info.LastLoginAt = time.Now()
		user_info.CreatedAt = time.Now()
		user_info.UpdatedAt = time.Now()
		id, db_err := user_info.Create(s.db.GetDbW().WithContext(ctx))
		if db_err!= nil{
			return "", err
		}
		jwt_st := jwt.New(id, phone_number, cfg_jwt.SecretKey, time.Duration(cfg_jwt.ExpiresAt) * time.Hour)
		//4. 返回token
		token, err := jwt_st.GenToken()
		return token, err
	}else{
		jwt_st := jwt.New(info.Id, phone_number, cfg_jwt.SecretKey, time.Duration(cfg_jwt.ExpiresAt) * time.Hour)
		//4. 返回token
		token, err := jwt_st.GenToken()
		return token, err
	}
	
}